/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.servico;

import br.com.foxinline.modelo.MicroArea;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author ely
 */
@Stateless
public class MicroAreaServico extends ServicoGenerico<MicroArea> {

    public MicroAreaServico() {
        super(MicroArea.class);
    }

    public List<MicroArea> findMicroArea(MicroArea microArea) {
        String sql = "select m from MicroArea m ";

        sql += " WHERE ";

        if (microArea.getNome() != null && !microArea.getNome().equals("")) {
            sql += " lower(m.nome) like lower(:nome) and ";
        }

        if (microArea.getCodigo() != null && !microArea.getCodigo().equals("")) {
            sql += " lower(m.codigo) like lower(:codigo) and ";
        }

        sql += " 1=1 AND m.ativo = TRUE Order by m.nome ASC";
        System.out.println(sql);

        Query query = getEntityManager().createQuery(sql);

        if (microArea.getNome() != null && !microArea.getNome().equals("")) {
            query.setParameter("nome", "%" + microArea.getNome() + "%");
        }

        if (microArea.getCodigo() != null && !microArea.getCodigo().equals("")) {
            query.setParameter("codigo", microArea.getCodigo());
        }

        return query.getResultList();
    }

    public List<MicroArea> autocomplete(String nome) {
        if (nome != null && !nome.isEmpty()) {
            return pesquisarTodos();
        }
        String sql = "Select m from " + MicroArea.class.getSimpleName() + " m where lower(m.nome) like lower(:nome)";

        Query query = getEntityManager().createQuery(sql);

        query.setParameter("nome", "%" + nome + "%");

        return query.getResultList();
    }

    public Long QtdFamiliaMicroArea(MicroArea microArea) {
        String sql = "SELECT count(i.id) FROM CadastroDomiciliar i JOIN i.profissional p WHERE p.microArea = :micro";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("micro", microArea);
        return (Long) query.getSingleResult();
    }
}
